# frozen_string_literal: true

class RuleService < ApplicationService
  class << self
    def create(params)
      Rule.transaction do
        rule = Rule.create! params.permit(:type, :name, :description)
        draft = rule.create_draft_entity! params.require(:draft_entity_attributes).permit(:type, :policy)
        draft.schema = Schema.find(params[:schema_id]) if params[:schema_id]

        { code: 0, message: 'success', rule: rule.as_json(rule_to_json_fmt) }
      end
    rescue StandardError => e
      logger.error e
      { code: 1, message: e.message }
    end

    def update(id, params)
      rule = Rule.find id
      Rule.transaction do
        rule.update! params.slice(:name, :description)
        rule.draft.update_draft(params[:draft]) if params[:draft].present?
      end
      # rule
      { code: 0, message: 'success', rule: rule.as_json(rule_to_json_fmt) }
    end

    def destroy(id)
      Rule.destroy(id)
      { code: 0, message: 'success' }
    end

    def search(params)
      rules = Rule.filter_name(params[:name]).filter_type(params[:type]).filter_status(params[:status])
      total = rules.count
      rules = rules.page_info(params[:page_size], params[:page_no])
      { code: 0, message: 'success', total: total, rules: rules.as_json }
    end

    def show(id)
      rule = Rule.find(id)
      { code: 0, message: 'success', rule: rule.as_json(rule_to_json_fmt) }
    end

    def show_by_uuid(uuid)
      rule = Rule.find_by! uuid: uuid
      { code: 0, message: 'success', rule: rule.as_json(rule_to_json_fmt) }
    end

    def validate_by_uuid(uuid)
      rule = Rule.find_by! uuid: uuid

      rule.validate
      { code: 0, message: 'success' }
    end

    def deploy_by_uuid(uuid)
      rule = Rule.find_by! uuid: uuid

      rule.validate

      rule.deploy
    end

    def fire(uuid, params)
      rule = Rule.find_by! uuid: uuid
      rule.fire(params)
    end

    private

    def rule_to_json_fmt
      {
        include: {
          draft: {
            only: %i[id type stage policy version status updated_at],
            include: {
              schema: {
                only: %i[id name description status]
              }
            }
          },
          product_entities: {
            only: %i[id type stage policy version status created_at updated_at],
            include: {
              schema: {
                only: %i[id name description status]
              }
            }
          }
        }
      }
    end
  end
end
